package org.lyl.taobao.controller.filter;

import org.lyl.taobao.api.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Re
 * @Date: 2021/4/16 11:05
 */
@WebFilter("/*")
public class AccessToIntercept implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化访问拦截");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        String path = String.valueOf(request1.getRequestURL());
        if (path.contains("/login.jsp")||path.contains("/registerUser.jsp")||path.contains("/upload")||path.contains("/registerUser")){
            chain.doFilter(request1,response1);
            return;
        }
        User user = (User) request1.getSession().getAttribute("user");
        if (user != null) {
            chain.doFilter(request1,response1);
            return;
        }
        response1.sendRedirect("registerUser.jsp");
    }

    @Override
    public void destroy() {
        System.out.println("拦截器被销毁");
    }
}
